package com.android.kotlincoroutinemvvmdemo.hook

import android.util.Log
import java.lang.reflect.Proxy

object GlobalActivityHookHelper {

    private const val TAG = "GlobalActivityHookHelper"

    fun hook() {
        try {
            val atmClazz = Class.forName("android.app.ActivityTaskManager")
            //API33之后不允许反射获取getService
            val methodGetService = atmClazz.getDeclaredMethod("getService")
            val atmsObj = methodGetService.invoke(null)

            val proxyATMClazz = Class.forName("android.app.ActivityTaskManager")
            val proxyATM = Proxy.newProxyInstance(
                Thread.currentThread().contextClassLoader,
                arrayOf(proxyATMClazz)
            ) { proxy, method, args ->
                if ("startActivity" == method?.name) {
                    Log.d(TAG, "object : InvocationHandler")
                }
                method?.invoke(atmsObj, *args.orEmpty())
            }

            val field = atmClazz.getDeclaredField("IActivityTaskManagerSingleton")
            field.isAccessible = true
            val fieldObj = field.get(null)

            val singletonClazz = Class.forName("android.util.Singleton")
            val instanceField = singletonClazz.getDeclaredField("mInstance")
            instanceField.isAccessible = true
            instanceField.set(fieldObj, proxyATM)
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }
}